using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using UnityEngine.Android;
using System.Collections.Generic;

public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    public static List<int> unlockLevel;
    //public static int LevelMax;
    public static int CurLevel;
    public static bool useAudio;
    static string path;
    public bool UseEnergy = false;
    public bool PC = true;

    public static int Energy;
    public static int maxEnergy;

    AudioClip changeClip;
    AudioClip changeClipBack;
    AudioClip buttonClip1;
    AudioClip scoreClip;
    AudioClip playerClip1;
    AudioClip playerClip2;

    AudioSource audioSource;

    List<string> permissionList = new List<string>();

    private void Awake()
    {
        maxEnergy = 10;
        useAudio = true;

        if (instance==null)
            instance = this;
        else
            Destroy(this);

        DontDestroyOnLoad(gameObject);

        audioSource = GetComponent<AudioSource>();

        changeClip = Resources.Load<AudioClip>("ChangeClip");
        changeClipBack = Resources.Load<AudioClip>("ChangeClipBack");
        buttonClip1 = Resources.Load<AudioClip>("Button1");
        scoreClip = Resources.Load<AudioClip>("GetScore");
        playerClip1 = Resources.Load<AudioClip>("PlayerScale1");
        playerClip2 = Resources.Load<AudioClip>("PlayerScale2");
    }

    private void Start()
    {
        path = Application.persistentDataPath + "/data";
        //if (File.Exists(path + "/pl.b"))
        //{
        //    InitGame();
        //}
        InitGame();

        permissionList.Add(Permission.ExternalStorageWrite);

        if(Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
        {
            Permission.RequestUserPermission(Permission.ExternalStorageWrite);
        }

        if (Permission.HasUserAuthorizedPermission(Permission.Microphone))
        {
            Permission.RequestUserPermission(Permission.Microphone);
        }
    }

    public void InitGame()
    {
        print(path);
        unlockLevel = ReadUnlockLevel();
        Energy = maxEnergy;
        if (UseEnergy)
        {
            DateTime lastTime = ReadEnergyTime();
            TimeSpan time = DateTime.Now - lastTime;
            string str = time.ToString();
            string[] strs = str.Split('.');

            if (time.ToString() == "00:00:00")
            {
                return;
            }

            if (strs.Length == 2)
            {
                string[] tm = strs[0].Split(':');

                int sec = int.Parse(tm[0]) * 60 * 60 + int.Parse(tm[1]) * 60 + int.Parse(tm[2]);

                Energy += (int)(sec * 1.0f / (10 * 60));
            }
            else if (strs.Length == 3)
            {
                string[] tm = strs[1].Split(':');

                int sec = int.Parse(strs[0]) * 24 * 60 * 60 +
                    int.Parse(tm[0]) * 60 * 60 + int.Parse(tm[1]) * 60 + int.Parse(tm[2]);

                Energy += (int)(sec * 1.0f / (10 * 60));
            }
            Energy = Energy > maxEnergy ? maxEnergy : Energy;
        }
    }

    public static void SetAudioEnable()
    {
        AudioSource[] audioSources = FindObjectsOfType<AudioSource>();
        for(int i=0; i<audioSources.Length; i++)
        {
            audioSources[i].enabled = useAudio;
        }
    }

    public static void UnlockLevel(int lvl)
    {
        if (path==null) return;
        List<int> list = ReadUnlockLevel();
        if (list.Contains(lvl)) return;

        unlockLevel = list;
        string content = "";

        for(int i=0; i< list.Count; i++)
        {
            content += list[i] + " ";
        }
        content += lvl;

        if (!File.Exists(path + "/data.dt"))
        {
            File.Create(path + "/data.dt").Dispose();
        }
        File.WriteAllText(path + "/data.dt", content, Encoding.UTF8);

        unlockLevel.Add(lvl);
    }

    static List<int> ReadUnlockLevel()
    {
        List<int> re = new List<int>();
        //print(!Directory.Exists(path));
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        //if(File.Exists(path + "/data.da"))
        //{
        //    string oldlvl = File.ReadAllText(path + "/data.da");
        //    int lvlmax = int.Parse(oldlvl);
        //    for(int i=0; i<lvlmax; i++)
        //    {
        //        re.Add(i + 1);
        //    }
        //}
        if (!File.Exists(path + "/data.dt"))
        {
            File.Create(path + "/data.dt").Dispose();
            File.WriteAllText(path + "/data.dt", "1", Encoding.UTF8);
            re.Add(1);
            return re;
        }
        else
        {
            string lvlstr = File.ReadAllText(path + "/data.dt");
            string[] levelstrs = lvlstr.Split(' ');
            for(int i=0; i<levelstrs.Length; i++)
            {
                re.Add(int.Parse(levelstrs[i]));
            }
            return re;
        }
    }

    public static void LoadLevel(int levelID)
    {
        if(instance.UseEnergy && levelID>=1)
        {
            if(Energy <= 0)
            {
                (UIManagerBase.Instance as UImanager).ShowAddEnergy();
                return;
            }
            else
            {
                Energy--;
                RecordEnergyTime();
            }
        }
        MessageManager.Clear();
        ImageAnimation imageAnimation = GameObject.FindGameObjectWithTag("FadePanel").GetComponent<ImageAnimation>();
        imageAnimation.BindEndAction(0, () => { SceneManager.LoadScene(levelID + 1); });
        imageAnimation.Play(0);
        CurLevel = levelID;
        Resources.UnloadUnusedAssets();

        //VideoRecorder.EndRecord();
    }

    public static void RecordEnergyTime()
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        if (!File.Exists(path + "/data.er"))
        {
            File.Create(path + "/data.er").Dispose();
        }
        string content = DateTime.Now.Year + " " + DateTime.Now.Month + " " + DateTime.Now.Day
            + " " + DateTime.Now.Hour + " " + DateTime.Now.Minute + " " + DateTime.Now.Second + " " +Energy;
        File.WriteAllText(path + "/data.er", content, Encoding.UTF8);
    }

    static DateTime ReadEnergyTime()
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        if (File.Exists(path + "/data.er"))
        {
            string str = File.ReadAllText(path + "/data.er");
            string[] dates = str.Split(' ');

            Energy = int.Parse(dates[6]);

            return new DateTime(int.Parse(dates[0]), int.Parse(dates[1]), int.Parse(dates[2]),
                int.Parse(dates[3]), int.Parse(dates[4]), int.Parse(dates[5]));
        }
        return DateTime.Now;
    }

    public void PlayerChangeAudio()
    {
        if (!audioSource.enabled) return;
        audioSource.clip = changeClip;
        audioSource.time = 0.22f;
        audioSource.pitch = 2;
        audioSource.Play();
    }

    public void PlayerChangeBackAudio()
    {
        if (!audioSource.enabled) return;
        audioSource.clip = changeClipBack;
        audioSource.time = 0.025f;
        audioSource.pitch = 2;
        audioSource.Play();
    }

    public void PlayerTouchAudio()
    {
        if (!audioSource.enabled) return;
        audioSource.clip = buttonClip1;
        audioSource.time = 0.025f;
        audioSource.pitch = 2;
        audioSource.Play();
    }

    public void PlayerGetScoreAudio()
    {
        if (!audioSource.enabled) return;
        audioSource.clip = scoreClip;
        audioSource.time = 0.025f;
        audioSource.pitch = 1;
        audioSource.Play();
    }

    public void PlayPlayerAudio(bool b)
    {
        if (!audioSource.enabled) return;
        if (b)
        {
            audioSource.clip = playerClip1;
        }
        else
        {
            audioSource.clip = playerClip2;
        }
        audioSource.time = 0.1f;
        audioSource.pitch = 5;
        audioSource.Play();
    }
}
